#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

// 条件变量
// 全局初始化
// pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 等待pthread_cond_wait（pthread_cond_t*, pthread_mutex_t*）
// 唤醒某个 pthread_cond_signal
// 唤醒所有 pthread_cond_broadcast
int tick = 10000;
// 单纯的互斥，可以保证线程安全
// 不一定合理或者高效
void *threadRoutine(void *argc)
{
    std::string name = static_cast<const char *>(argc);
    while (true)
    {
        /* code */
        // sleep(1);
        // 加锁和解锁之间，往往需要访问临界资源，所以需要判断
        pthread_mutex_lock(&mutex);
        if (tick > 0)
        {
            std::cout << name << "get a new tick" << tick << std::endl;
            tick--;
            usleep(1000);
        }
        else
        {
            std::cout << "没有票了" << name << std::endl;
            pthread_cond_wait(&cond, &mutex);
            // 线程在等待时会自动释放锁
            // 线程被唤醒，是在临界区内唤醒，当线程被唤醒，在pthread_cond_wait返回的时候，需要重新申请并持有锁
            // 当线程被唤醒的时候，重新申请并持有锁本质也是要参与到锁的竞争
        }
        // 添加条件变量
        // pthread_cond_wait(&cond, &mutex);
        // std::cout << "i am a new thread" << name << std::endl;
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, threadRoutine, (void *)"thread1");
    pthread_create(&t2, nullptr, threadRoutine, (void *)"thread2");
    pthread_create(&t3, nullptr, threadRoutine, (void *)"thread3");

    sleep(5);
    while (true)
    {
        // pthread_cond_signal(&cond);
        // pthread_cond_broadcast(&cond);

        sleep(8);
        pthread_mutex_lock(&mutex);
        tick += 500;
        pthread_mutex_unlock(&mutex);
        pthread_cond_broadcast(&cond);
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
}